package com.icexxx.lathe;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
 * 防止重复提交拦截器
 * 
 * @author Administrator
 */
public abstract class AbstractRepeatInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            Repeat annotation = method.getAnnotation(Repeat.class);
            if (annotation != null) {
                if (!this.handle(request)) {
                    String message = messageInfo();
                    String code = codeInfo();
                    String msg = msgInfo();
                    int codeValue = codeValueInfo();
                    String concatMessageInfo = concatMessage(message, code, msg, codeValue);
                    MessageManager.message(concatMessageInfo, response);
                    return false;
                }
            }
            return true;
        } else {
            return super.preHandle(request, response, handler);
        }
    }

    /**
     * 校验是否为重复提交
     * 
     * @param request http请求
     * @return 是否为重复提交
     */
    protected abstract boolean handle(HttpServletRequest request);

    /**
     * 错误消息
     * 
     * @return 错误消息
     */
    protected abstract String messageInfo();

    /**
     * 消息编码键名称
     * 
     * @return 消息编码键名称
     */
    protected abstract String codeInfo();

    /**
     * 消息内容键名称
     * 
     * @return 消息内容键名称
     */
    protected abstract String msgInfo();

    /**
     * 消息编码数值
     * 
     * @return 消息编码数值
     */
    protected abstract int codeValueInfo();

    /**
     * 拼接完整的错误消息
     * 
     * @param message   错误消息
     * @param code      消息编码键名称
     * @param msg       消息内容键名称
     * @param codeValue 消息编码数值
     * @return 完整的错误消息
     */
    protected abstract String concatMessage(String message, String code, String msg, int codeValue);

    /**
     * 获取session id
     * 
     * @return 获取的session id
     */
    protected abstract String sessionIdInfo();
}
